#include "GlTextureManager.h"

#include <D3DX11tex.h>
#include <algorithm>
#include <cstring>

namespace GraphicLibrary
{
	TextureManager *TextureManager::msSingleton(0);
	//------------------------------------------
	TextureManager::~TextureManager()
	{
		for(ContentArray::iterator i = mTextures.begin(); i != mTextures.end(); ++i)
			delete *i;
	}

	//------------------------------------------
	ID3D11ShaderResourceView* TextureManager::getTexture(const char *fileName)
	{
		ContentArray::iterator i = findPlace(fileName);
		if(i != mTextures.end() && !strcmp((*i)->mName, fileName))
			return (*i)->mTexture;

		ID3D11ShaderResourceView *tex = createTexture(fileName);	
		mTextures.insert(i, new Content(fileName, tex));
		return tex;
	}

	//------------------------------------------
	TextureManager::ContentArray::iterator TextureManager::findPlace(const char *name) const
	{
		class Less_ByName
		{
			public:
				inline bool operator () (const Content *left, const Content *right) const	{return strcmp(left->mName, right->mName) < 0;}
				inline bool operator () (const Content *left, const char *right) const	{return strcmp(left->mName, right) < 0;}
				inline bool operator () (const char *left, const Content *right) const	{return strcmp(left, right->mName) < 0;}
		};
		ContentArray::iterator i = std::lower_bound(const_cast<TextureManager*>(this)->mTextures.begin(), const_cast<TextureManager*>(this)->mTextures.end(), name, Less_ByName());
		return i;
	}

	//------------------------------------------
	ID3D11ShaderResourceView* TextureManager::createTexture(const char *fileName) const
	{
		ID3D11ShaderResourceView *tex = 0;
		HRESULT res = D3DX11CreateShaderResourceViewFromFile(mDevice, fileName, 0, 0, &tex, 0);
		if(res != S_OK)
			throw ElFileLoadError;
		return tex;
	}
}
